상속과 메서드 오버라이딩
✒️ 2025-05-19 10:25 내용 수정
Do it! 점프 투 파이썬(2017년 발행) 내용을 정리
상속
부모 클래스의 기능을 자식 클래스에서 물려받아 사용하는 것
- 객체 지향(객체 지향(Object Oriented))의 특징으로, 중복된 속성과 메서드를 제거하고 클래스 재사용에 용이하다.
- Java의 상속(상속(Inheritance))도 참고.
- Python에서 클래스를 상속 받으려면
class 클래스이름(부모클래스)를 사용한다.
class 클래스이름(부모클래스):
pass
- 부모 클래스를 물려 받으면 부모 클래스에서 구현한 메서드를 사용할 수 있다.
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color
def setdata(self, name, color):
self.name = name
self.color = color
def printfruit(self):
print(self.color, self.name)
def fullname(self):
return self.color + " " + self.name
class Food(Fruit):
pass
a = Food("chicken", "red")
a.printfruit()
- 자식 클래스에서 사용할 메서드를 구현하면 부모 클래스의 기능을 그대로 둔 채 기능을 확장하여 사용할 수 있다.
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color
def setdata(self, name, color):
self.name = name
self.color = color
def printfruit(self):
print(self.color, self.name)
def fullname(self):
return self.color + " " + self.name
class Food(Fruit):
def sell(self, price):
self.price = price
print(self.color, self.name, "for", f"${price}")
a = Food("chicken", "red")
a.printfruit()
a.sell(100)
메서드 오버라이딩
부모 클래스에서 구현한 메서드를 자식 클래스에서 같은 이름으로 다시 만드는 것
- Java의 메서드 오버라이딩(오버라이딩(Overriding)) 참고.
- 메서드 오버로드는 같은 이름의 메서드를 다른 매개변수 종류와 개수로 중복 정의하는 것이다.
- 오버라이딩은 상속 관계에서 상위 클래스(부모 클래스)가 상속해준 메서드의 내용을 하위 클래스(자식 클래스)에서 다시 정의하여 구현하는 것이다.
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color
def setdata(self, name, color):
self.name = name
self.color = color
def printfruit(self):
print(self.color, self.name)
def fullname(self):
return self.color + " " + self.name
class Food(Fruit):
def sell(self, price):
self.price = price
print(self.color, self.name, "for", f"${price}")
# 메서드 오버라이딩
def setdata(self, name, color, price):
self.name = name
self.color = color
self.price = price
b = Food("lemon", "yellow")
b.printfruit()
b.setdata("watermelon", "green and black", "50")
print(b.name, b.color, b.price)